<template>
  <md-nav-bar title="商品详情" backgroundColor="#ffffff"/>
  <view class="goods-detail-page">
    <!-- 商品图片 -->
    <image class="goods-img" :src="data.goodDetail.imageUrl" mode="aspectFill" />
    <!-- 商品价格和名称 -->
    <view class="goods-container">
      <view class="goods-info">
        <text class="goods-price">￥{{ formatUnitCentToYuan(data.goodDetail.price, 2) }}</text>
        <view class="goods-title">{{ data.goodDetail.title }}</view>
      </view>
      <view class="action-area">
        <!-- 分享 -->
        <md-share-btn :title="data.goodDetail.title" :image-url="data.goodDetail.imageUrl" :path="'/page/sub/my/shopDetail?spuId='+data.goodDetail.spuId+'&skuId='+data.goodDetail.skuId" />
      </view>
    </view>
    

    <!-- 音频播放区域 -->
    <view class="audio-section">
      <view class="audio-desc">
        <text>{{ data.goodDetail.description }}</text>
      </view>
      <view class="play-block">
        <!-- 播放音频 -->
        <md-audio v-if="data.goodDetail.musicUrl" hidetime :src="data.goodDetail.musicUrl" v-model:play="data.audioPlay">
          <image class="play-icon" @click="onPlayAudio" :src="data.audioPlay ? 'https://cdn.xmxiaomai.com/isong_static/music/%E6%9A%82%E5%81%9C.png' : 'https://cdn.xmxiaomai.com/isong_static/music/Group%2014.png'" />
        </md-audio>
      </view>

    </view>

    <!-- 底部操作栏 -->
    <view class="footer">
      <button class="contact-btn" open-type="contact" >
<!--        <image class="kefu-img" src="https://cdn.xmxiaomai.com/isong_static/square/%E5%AE%A2%E6%9C%8D.png" mode="aspectFill" />-->
         联系客服
      </button>
      <button class="buy-btn"
              :class="{ 'ios-disabled': isIOS }"
              :disabled="isIOS"
              @click="onBuy">{{ isIOS ? 'IOS暂不支持' : '立即购买' }}</button>
    </view>
  </view>
</template>

<script lang="ts" setup>
import {computed, reactive} from 'vue'
import { onLoad, onShareAppMessage, onShareTimeline } from '@dcloudio/uni-app';
import { formatUnitCentToYuan } from '@/utils/util';
import api from '@/api/index';
import type { User } from '@/api/data';
const data = reactive({
  goodDetail: {} as User.Order.Product,
  audioPlay: false
})
const isIOS = computed(() => {
  const {system} = wx.getSystemInfoSync()
  const config = uni.getStorageSync('config');
  const iosShowFlag = config?.iosShowFlag || false;
  return system.toLowerCase().includes('ios') && iosShowFlag;
});

function onPlayAudio() {
  data.audioPlay = !data.audioPlay
}
async function onBuy() {
  if (isIOS.value) {
    return;
  }
  const order = await fetchCreateOrderId();
  // 存完订单才会继续往下走
  if (order?.payOrderId) {
    fetchSubmit(order.payOrderId, order.orderId);
  }
}
// 创建订单
const fetchCreateOrderId = async () => {
  const _id = uni.getStorageSync('auth')?.userId;
  try {
    const res = await api.Order.purchaseProduct({
      memberId: _id,
      spuId: data.goodDetail.spuId,
    });
    return res?.data;
  } catch (error) {
    console.log(error)
    Toast(error?.data?.msg || '购买失败');
  }
  return undefined;
};

// 通过订单，提交支付
const fetchSubmit = async (payOrderId:number, orderId: number) => {
  const auth = uni.getStorageSync('auth');
  try {
    const res = await api.Pay.submit({
      id: payOrderId,
      channelCode: 'wx_lite', // 微信支付
      channelExtras: {
        openid: auth?.openid,
      },
    });
    const payConfig = JSON.parse(res.data?.displayContent || '');
    // 线上 弹出微信支付
    uni.requestPayment({
      provider: 'wxpay',
      orderInfo: {},
      nonceStr: payConfig?.nonceStr, // 随机字符串
      package: payConfig?.packageValue, // 固定值
      signType: payConfig?.signType,
      timeStamp: payConfig?.timeStamp, // 时间戳（单位：秒）
      paySign: payConfig?.paySign, // 签名，这里用的 MD5/RSA 签名
      async success(res) {
        uni.showModal({
          title: '提示',
          content: '购买成功',
          showCancel: false,
          success: res => {
            if (res.confirm) {
              uni.navigateTo({
                url: '/pages/sub/my/myOrder?orderId='+(orderId || ''),
              });
              
            }
          },
        });
      },
      fail(e) {
        fetchPayCancelOrder(auth?.userId, payOrderId);
      },
    });
  } catch (error) {}
  return undefined;
};

const fetchPayCancelOrder = async (memberId: number, payOrderId: number) => {
  try {
    await api.Order.cancelOrder({
      memberId,
      payOrderId,
    });
    Toast('订单取消');
  } catch (e) {}
};

// 获取商品详情
const fetchGetGoodsinfo = async (obj: any) => {
  try {
    const res = await api.Order.productDetail({
      spuId: obj.spuId,
      skuId: obj.skuId
    });
    data.goodDetail = Object.assign(data.goodDetail, res.data, {
      spuId: obj.spuId,
      skuId: obj.skuId
    });
  } catch (e) {}
};
onLoad((options: any) => {
  fetchGetGoodsinfo(options)
  const auth = uni.getStorageSync('auth');
  data.userId = auth?.userId;
});

// 分享
onShareAppMessage(res => {
  return {
    title: data.goodDetail.title || 'isong AI',
    imageUrl: data.goodDetail.imageUrl || 'https://cdn.xmxiaomai.com/isong_static/share.jpg',
    path: '/pages/sub/my/shopDetail?spuId=' + (data.goodDetail.spuId || '') + '&skuId=' + (data.goodDetail.skuId || '') + (data.userId ? ('&parentId=' + data.userId) : ''),
  };
});

onShareTimeline(() => {
  return {
    title: data.goodDetail.title || 'isong AI',
    imageUrl: data.goodDetail.imageUrl || 'https://cdn.xmxiaomai.com/isong_static/share.jpg',
    query: 'spuId=' + (data.goodDetail.spuId || '') + '&skuId=' + (data.goodDetail.skuId || '') + (data.userId ? ('&parentId=' + data.userId) : '')
  };
});

</script>

<style scoped lang="scss">
.goods-detail-page {
  background: #f7f7f7;
  min-height: 100vh;
  padding-bottom: 120rpx;
}
.goods-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #ffffff;
  border-bottom: 1rpx solid #eee;
  .action-area {
    padding-right: 30rpx;
  }
}
.goods-img {
  width: 100%;
  height: 750rpx;
  background: #ededed;
  margin-bottom: 0;
}
.play-icon {
  width: 80rpx;
  height: 80rpx;
  margin-top: 20rpx;
}
.goods-info {
  background: #fff;
  padding: 24rpx;
  
}
.goods-price {
  color: #ff8855;
  font-size: 42rpx;
  font-weight: bold;
  margin-bottom: 8rpx;
  display: block;
}
.goods-title {
  color: #222;
  font-size: 28rpx;
  margin-top: 8rpx;
}
.audio-section {
  background: #fff;
  padding: 24rpx;
  border-bottom: 1rpx solid #eee;
  position: relative;
  min-height: 200rpx;
}
.play-block {
  position: absolute;
  top: 20rpx;
  right: 10rpx;
}

.audio-box {
  width: 100%;
  height: 60rpx;
  border: 2rpx solid #bbb;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 16rpx;
}
.audio-desc {
  color: #333;
  font-size: 26rpx;
  line-height: 1.8;
  white-space: pre-wrap; /* 保留空白符序列，但是正常地进行换行 */
  word-wrap: break-word;
  min-height: 500rpx;
}
.footer {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  background: #fff;
  padding: 16rpx 0 24rpx 0;
  box-shadow: 0 -2rpx 8rpx #eee;
  display: flex;
  justify-content: center;
  z-index: 10;
}
.kefu-img {
  width: 50rpx;
  height: 50rpx;
}

.contact-btn {
  width: 40%;
  background: #33bffb;
  color: #fff;
  font-size: 32rpx;
  border-radius: 40rpx;
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  font-weight: bold;
  border: none;
}

.buy-btn {
  width: 40%;
  background: #ff8855;
  color: #fff;
  font-size: 32rpx;
  border-radius: 40rpx;
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  font-weight: bold;
  border: none;
}

</style>